import 'package:chathouse/model/pre_question_bean.dart';
import 'package:chathouse/model/response_bean.dart';
import 'package:chathouse/pages/questions/extent.dart';
import 'package:chathouse/pages/questions/next_question_page.dart';
import 'package:chathouse/public/Config.dart';
import 'package:chathouse/widgets/base_appbar.dart';
import 'package:chathouse/widgets/form_widgets/expert_dialog.dart';
import 'package:chathouse/widgets/form_widgets/question_dialog.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:chathouse/util/base_utils.dart';
import '../../model/expert_list_bean.dart';
import 'common_widget.dart';
import 'extent.dart';

//問題前置頁
class PreQuestionPage extends StatefulWidget {
  int serviceId;
  String serviceTitle;
  Color? titleColor;
  bool needGetExpertList;
  int disinfestationServiceId;
  PreQuestionPage(this.serviceId, this.serviceTitle, this.titleColor,
      {this.needGetExpertList = false,
      this.disinfestationServiceId = 0,
      Key? key})
      : super(key: key);

  @override
  State<PreQuestionPage> createState() => _PreQuestionPageState();
}

class _PreQuestionPageState extends State<PreQuestionPage> {
  PreQuestionBeanTool? preQuestionBeanTool;
  List<Map> paras = []; //问题答案,下一页参数
  Map p6 = {}; //temp 类型6用的 保存答案
  Map p9 = {}; //temp 类型9用的 保存答案
  Map<int, dynamic> tempMap = {};
  late PreQuestionController controller;

  //专家推荐，专家弹窗答题
  ExpertListBeanTool? expertListBeanTool;
  PreQuestionBeanTool? expertQuestionBeanTool;
  ExpertItemBean? selectExpertItemBean;

  @override
  void initState() {
    super.initState();
    controller = PreQuestionController();
    getQuestionData();
    if (widget.needGetExpertList) {
      getExpertList();
      getExpertQuestion();
    }
  }

  @override
  void dispose() {
    super.dispose();
    controller.dispose();
  }

  void getQuestionData() {
    Obj.showLoading();
    Apis.listByServiceId({"serviceId": widget.serviceId}).then((response) {
      Obj.dismissLoading();
      try {
        preQuestionBeanTool =
            PreQuestionBeanTool.fromJson(response?.data ?? {});
        debugPrint(response.toString());
        if (preQuestionBeanTool?.isRequestSuccess ?? false) {
          setState(() {});
        }
      } catch (e) {
        debugPrint(e.toString());
      }
    }).catchError((error) => {Obj.dismissLoading(), setState(() {})});
  }

  void getExpertList() {
    Obj.showLoading();
    Apis.getExpList(widget.serviceId).then((response) {
      Obj.dismissLoading();
      try {
        expertListBeanTool = ExpertListBeanTool.fromJson(response?.data ?? {});
        //提交頁面顯示選擇專家
        if(canShowExpertListDialog()) {
          controller.subSelectExpert = (Function callback) {
            showExpertListDialog(callback);
          };
        }
      } catch (e) {
        debugPrint(e.toString());
      }
    }).catchError((error) => {Obj.dismissLoading(), setState(() {})});
  }

  bool canShowExpertListDialog() {
    return (expertListBeanTool?.isRequestSuccess ?? false) && expertListBeanTool!.rows!.isNotEmpty;
  }

  void showExpertListDialog(Function callback) async{
    await Get.dialog(ExpertDialogWidget(
        widget.serviceTitle, expertListBeanTool, (index) {
      selectExpertItemBean = expertListBeanTool!.rows![index];
      Get.back();
    }));
    if(selectExpertItemBean == null) {
      callback();
      return;
    }
    Obj.showLoading();
    Apis.subSelectExpert(selectExpertItemBean!.toJson()).then((response) {
      Obj.dismissLoading();
      try {
        ResponseBean responseBean =
        ResponseBean.fromJson(response?.data ?? {});
        if (responseBean?.isRequestSuccess ?? false) {
          debugPrint("選擇專家成功");
        }
        callback();
      } catch (e) {
        debugPrint(e.toString());
        callback();
      }
    }).catchError(
            (error) => {Obj.dismissLoading(), callback(), setState(() {})});
  }


  void getExpertQuestion() {
    Obj.showLoading();
    Apis.getExpQuestionList(widget.disinfestationServiceId).then((response) {
      Obj.dismissLoading();
      try {
        expertQuestionBeanTool =
            PreQuestionBeanTool.fromJson(response?.data ?? {});
        showExpQuestionDialog();
      } catch (e) {
        debugPrint(e.toString());
      }
    }).catchError((error) => {Obj.dismissLoading(), setState(() {})});
  }

  void showExpQuestionDialog() {
    var bean = (expertQuestionBeanTool?.rows != null &&
        expertQuestionBeanTool!.rows!.isNotEmpty)
        ? expertQuestionBeanTool!.rows!.first
        : PreQuestionBean();
    if ((bean.list ?? []).isEmpty) {
      return;
    }
    Future.delayed(const Duration(milliseconds: 200),(){
      Get.dialog(QuestionDialogWidget(bean, (val) {
        Map<String, dynamic> para = {
          "problemId": bean.problemId,
          // "pagesNum": page ?? 1,
          "pagesNum": bean.pagesNum,
          "serviceId": preQuestionBeanTool?.serviceId ?? widget.serviceId,
          "firstProblemId": bean.problemId,
          "required": bean.required,
        };
        para["firstOptionCode"] = val.toParaString();
        para["optionValue"] = val
            .map((e) {
          return bean?.list?.firstWhere((element) {
            return element.optionCode.toString() == e;
          }).optionValue ??
              "";
        })
            .toList()
            .toParaString();
        paras.add(para);
        debugPrint("paras = $paras");
        Get.back();
      }));
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: getAppBar(
            leading: IconButton(
                onPressed: () {
                  Get.back();
                },
                icon: ImageUtils.image(Res.question_close,
                    width: 28.w, height: 28.w)),
            title: preQuestionBeanTool?.serviceName ?? widget.serviceTitle,
            titleColor: widget.titleColor ?? Colors.black),
        body: Column(
          children: [
            Expanded(child: ListView(children: getSubWidget())),
            Container(
              padding: EdgeInsets.only(
                  left: 26.w, right: 26.w, bottom: 20.w, top: 20.w),
              child: Obx(() {
                return Row(
                  children: [
                    Expanded(
                        child: Text("上頁",
                                style: getTextStyle(20.sp,
                                    color: Colors.white,
                                    fontType: FontType.BOLD))
                            .setContainer(
                                alignment: Alignment.center,
                                height: 38.w,
                                decoration: BoxDecoration(
                                    color: MyColors.gary_155155155,
                                    borderRadius: BorderRadius.all(
                                        Radius.circular(19.w))))
                            .setOnClickListener(() {
                      Get.back();
                    })),
                    SizedBox(width: 20.w),
                    Expanded(
                      child: Text("下一頁",
                              style: getTextStyle(20.sp,
                                  color: Colors.white, fontType: FontType.BOLD))
                          .setContainer(
                              alignment: Alignment.center,
                              height: 38.w,
                              decoration: BoxDecoration(
                                  color: controller.canNextBtnClick.value
                                      ? MyColors.brow_25118177
                                      : MyColors.gary_155155155,
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(19.w))))
                          .setOnClickListener(() {
                        nextButtonClick();
                      }),
                    ),
                  ],
                );
              }),
            )
          ],
        ));
  }

  //14种问题
  List<Widget> getSubWidget() {
    return getCommandSubWidget(preQuestionBeanTool, widget.serviceId,
        setNextButtonCanClick, paras, p6, p9, tempMap);
  }

  void setNextButtonCanClick() {
    bool checkParas = true;
    for (var element in paras) {
      if (element["required"] == "0") {
        if (element["firstOptionCode"] == null ||
            element["firstOptionCode"] == "") {
          checkParas = false;
        }
      }
    }
    controller.canNextBtnClick.value = checkParas;
  }

  void nextButtonClick() {
    if (!controller.canNextBtnClick.value) return;
    Obj.showLoading();
    Apis.nextPage(paras).then((response) {
      Obj.dismissLoading();
      try {
        var resQuestionBeanTool =
            PreQuestionBeanTool.fromJson(response?.data ?? {});
        debugPrint(response.toString());
        if (resQuestionBeanTool.isRequestSuccess) {
          debugPrint("page=1");
          //配置 最后提交页 参数
          List<Map> tempList = [];
          for (var element in paras) {
            PreQuestionBean? preQuestionBean =
                preQuestionBeanTool?.rows?.firstWhere((model) {
              return model.problemId == element["problemId"];
            });
            Map<String, dynamic> submitParas = {
              "optionCode": element["firstOptionCode"],
              "optionValue": element["optionValue"],
              "problemId": preQuestionBean?.problemId,
              "problemName": preQuestionBean?.problemName,
              "problemSort": preQuestionBean?.problemSort,
              "problemType": preQuestionBean?.problemType,
            };
            // controller.appParas.add(submitParas);
            tempList.add(submitParas);
          }
          controller.appParas[1] = tempList;
          Get.to(
              NextQuestionPage(
                  2,
                  resQuestionBeanTool.serviceId ??
                      preQuestionBeanTool?.serviceId ??
                      widget.serviceId,
                  resQuestionBeanTool.serviceName ??
                      preQuestionBeanTool?.serviceName ??
                      widget.serviceTitle,
                  resQuestionBeanTool,
                  controller,
                  widget.titleColor),
              preventDuplicates: false);
        }
      } catch (e) {
        debugPrint(e.toString());
      }
    }).catchError((error) => {Obj.dismissLoading(), setState(() {})});
  }

  String? getOptionValueByOptionCode(int? problemId, String? optionCode) {
    if (optionCode == null || optionCode.isEmpty) return "";
    PreQuestionBean? preQuestionBean =
        preQuestionBeanTool?.rows?.firstWhere((model) {
      return model.problemId == problemId;
    });
    return preQuestionBean?.list?.firstWhere((element) {
      return element.optionCode.toString() == optionCode;
    }).optionValue;
  }
}

class PreQuestionController extends GetxController {
  var canNextBtnClick = false.obs;
  // List<Map> appParas = []; //所以问题，最后提交的参数。
  Map<int, List<Map>> appParas = {}; //所以问题，最后提交的参数。{index paras}

  List<Map> getFormatAppParas() {
    List<Map> lm = [];
    appParas.forEach((key, value) {
      lm.addAll(value);
    });
    return lm;
  }

  Function? subSelectExpert;
}
